import XLSX from "xlsx-js-style";
import { mergeTableData, formatTabletoExcel } from "./common-excel";
import { message } from "antd";
import { getAuditYearApi } from "../cpas-table/ExcelGrid/api/DesignTableApi";
import { consts } from "./consts";
import { nanoid } from "nanoid";
import BigNumber from "bignumber.js";
import _ from "lodash";
/**
 * 系统名称
 */
export var SystemName;
(function (SystemName) {
    SystemName[SystemName["SINGLE"] = 0] = "SINGLE";
    SystemName[SystemName["MERGE"] = 1] = "MERGE";
    SystemName[SystemName["UNKNOW"] = 2] = "UNKNOW";
})(SystemName || (SystemName = {}));
/**
 * 合并系统法定，合并用
 */
export var MergeType;
(function (MergeType) {
    MergeType["HB_FD"] = "HBC_FD";
    MergeType["HB_HBYDT"] = "HBC_HBY";
    MergeType["DT_FD"] = "DT_FD";
    MergeType["DT_HBYDT"] = "DT_HBY";
    MergeType["TEMPLATE"] = "TEMPLATE";
    MergeType["UNKNOW"] = "UNKNOW";
})(MergeType || (MergeType = {}));
/**
 * 合并系统法定，合并用
 */
export const MergeTypeConfig = {
    HB_FD: "HB_FD",
    HB_HBYDT: "HB_HBYDT",
    DT_FD: "DT_FD",
    DT_HBYDT: "DT_HBYDT",
    UNKNOW: "UNKNOW",
};
/**
 * 获取当前是单体还是合并系统
 */
export function getCurrentSysName() {
    if (!window.sessionStorage.getItem("electronParams")) {
        return SystemName.SINGLE;
    }
    const electronParams = JSON.parse(window.sessionStorage.getItem("electronParams")).params;
    if (electronParams) {
        if (electronParams.sysName === "merge") {
            return SystemName.MERGE;
        }
        else {
            return SystemName.SINGLE;
        }
    }
    else {
        return SystemName.UNKNOW;
    }
}
/**
 * 判断当前合并层是法定还是合并用
 */
export function getMergeType() {
    if (!window.sessionStorage.getItem("electronParams")) {
        return MergeType.UNKNOW;
    }
    const electronParams = JSON.parse(window.sessionStorage.getItem("electronParams")).params;
    // 仅在合并下有效
    if (getCurrentSysName() !== SystemName.MERGE) {
        return MergeType.UNKNOW;
    }
    if (electronParams && electronParams.ZcbfID) {
        const zcbfid = electronParams.ZcbfID;
        if (zcbfid.endsWith("-HBC") || zcbfid.endsWith("-MFHB")) {
            return MergeType.HB_FD; // 合并层-法定
        }
        else if (zcbfid.endsWith("-HBC-HBYDT") ||
            zcbfid.endsWith("-MFHB-HBYDT")) {
            return MergeType.HB_HBYDT; // 合并层-合并用
        }
        else if (zcbfid.endsWith("-HBYDT")) {
            return MergeType.DT_HBYDT; //单体层-合并用
        }
        else {
            return MergeType.DT_FD; //单体层法定
        }
    }
    else {
        return MergeType.UNKNOW;
    }
}
/**
 * 根据组成部分ID返回合并系统类型
 * @param zcbfid
 * @returns
 */
export function getHbTypeByZcbfid() {
    if (!window.sessionStorage.getItem("electronParams")) {
        return MergeType.UNKNOW;
    }
    const electronParams = JSON.parse(window.sessionStorage.getItem("electronParams")).params;
    // 仅在合并下有效
    if (getCurrentSysName() !== SystemName.MERGE) {
        return MergeType.UNKNOW;
    }
    if (getCurrentSysName() === SystemName.MERGE &&
        electronParams &&
        electronParams.ZcbfID) {
        const zcbfid = electronParams.ZcbfID;
        const hb_suffix_arr = zcbfid.split("-");
        const hb_first_prefix = hb_suffix_arr.shift();
        const hb_last_suffix = hb_suffix_arr.pop();
        const hb_two_suffix = hb_suffix_arr.pop();
        if (hb_first_prefix === "TemplateData") {
            return MergeType.TEMPLATE; //模板类型
        }
        let hbType;
        switch (hb_last_suffix) {
            case "HBC":
                hbType = MergeType.HB_FD; //合并层法定
                break;
            case "HBYDT":
                if (hb_two_suffix === "HBC") {
                    hbType = MergeType.HB_HBYDT; //合并层合并用
                }
                else if (hb_two_suffix === "MFHB") {
                    hbType = MergeType.HB_FD; //合并层合法定
                }
                else {
                    hbType = MergeType.DT_HBYDT; //单体层合并用
                }
                break;
            default: //单体层法定
                hbType = MergeType.DT_FD;
                break;
        }
        return hbType;
    }
}
/**
 * nanoid 10位, 代替GUID的生成，减小存储
 * 优点: 生成速度快，存储量小
 * 缺点: 算法采用随机算法，数据量大的时候，唯一性比GUID查
 * nanoid(10)表示生成一个长度为10的NanoID标识符。假设使用默认的字符集，包括大小写字母和数字，共62个字符。那么理论上，它可以生成的不重复ID的数量为62的10次方，即约等于8.39亿（839,299,365）个不重复的ID。
 */
export function nanoid10() {
    return nanoid(10);
}
// 约等于4.77乘以10的28次方
export function nanoid16() {
    return nanoid(16);
}
/**
 * 千分位格式化
 */
export const formatNumberToThousand = (num) => {
    let res = num.toString().replace(/\d+/, function (n) {
        // 先提取整数部分
        return n.replace(/(\d)(?=(\d{3})+$)/g, function ($1) {
            return $1 + ",";
        });
    });
    return res;
};
export const guid = () => {
    return "xxxxxxxxxxxx4xxxyxxxxxxxxxxxxxxx".replace(/[xy]/g, (c) => {
        const r = (Math.random() * 16) | 0, v = c == "x" ? r : (r & 0x3) | 0x8;
        return v.toString(16);
    });
};
/**
 * 父节点丢失处理成空或者指定id
 * @param data
 */
export function resetPidIfNotFound(data, pid) {
    const map = new Map(data.map((item) => [item.id, item]));
    for (const item of data) {
        if (item.pid && !map.has(item.pid)) {
            if (pid) {
                item.pid = pid;
            }
            else {
                item.pid = null;
            }
            if (item.parentId) {
                item.parentId = null;
            }
        }
    }
    return data;
}
export function EntrySynchronizationMethod(params) {
    const paramsObj = {
        argType: "c",
        u: params.usercode,
        p: params.password,
        zcbfid: params.zcbfid,
        BusType: params.BusType ? params.BusType : 2,
        BusID: params.BusID,
        BusAction: "s",
        ShowBusFrm: false,
        callback: {
            type: "http",
            address: `${localStorage.getItem("cpasApiUrl")}/office/syncState`,
            token: localStorage.getItem("cpasToken"),
            tag: params.tag,
        },
    };
    const Parameter = JSON.stringify(paramsObj);
    console.log(`cpas://OpenLocalFile/?fileName=./CpasCloudSvr/CpasCloudSvr.exe&params=${Parameter}`);
    window.location.href = `cpas://OpenLocalFile/?fileName=./CpasCloudSvr/CpasCloudSvr.exe&params=${Parameter}`;
}
/**
 * 重新排序一下树节点,按照深度递归的顺序，平铺节点
 */
export function sortTreeByChildren(data, sourceTreeData) {
    // 从库里查出来的数据会保证同级下的顺序数组，order by pid,orderNumber.
    // 所以直接转成树形结构会保证同级下的顺序
    // 由于数据库里没有存储level层级，所以需要先转成树形结构，再按照深度递归的方式转成平铺的数组
    //const dataId = await getDataId()
    // 获取原树
    //const resData = await getLeftTreeList(dbname, dataId);
    const sourceTreeArr = [];
    // 按照深度递归平铺原树
    deepTree(convertLevelToTree(sourceTreeData), sourceTreeArr);
    // 检测无父ID的提升 , 勾稽汇总的树
    const resetTargetData = resetPidIfNotFound(data);
    // 按照原树进行填充位置
    let sort_arr = new Array(sourceTreeArr.length).fill(null);
    // 进行位置对比，将勾稽汇总的树。按照源树进行排序
    for (let i = 0; i < resetTargetData.length; i++) {
        for (let j = 0; j < sourceTreeArr.length; j++) {
            if (resetTargetData[i].id === sourceTreeArr[j].id) {
                sort_arr[j] = resetTargetData[i];
            }
        }
    }
    //过滤掉无用Null占位
    sort_arr = sort_arr.filter((item) => item !== null);
    return sort_arr;
}
//循环查找父节点
export function loopParentTreeList(data, allData) {
    if (!data || !data.length) {
        return;
    }
    let result = data.slice();
    const parentIds = [];
    for (let i = 0; i < data.length; i++) {
        const current = data[i];
        // const res = result.filter((item: any) => item.fid === current.fid);
        if (current.parentId && !parentIds.includes(current.parentId)) {
            parentIds.push(current.parentId);
        }
    }
    if (parentIds && parentIds.length) {
        for (let i = 0; i < parentIds.length; i++) {
            const parentId = parentIds[i];
            const parentData = allData.filter((item) => item.fid === parentId);
            if (parentData && parentData.length) {
                const res = loopParentTreeList(parentData, allData);
                if (res && res.length) {
                    result = result.concat(res);
                }
            }
        }
    }
    result.map((item) => {
        item.expanded = true;
    });
    return unique(result);
}
/**
 * 按照深度递归的顺序，平铺节点
 */
const deepTree = (data, arr = []) => {
    for (let i = 0; i < data.length; i++) {
        const item = data[i];
        const clone_item = _.cloneDeep(item);
        delete clone_item.children;
        arr.push(clone_item);
        if (item.children && item.children.length) {
            deepTree(item.children, arr);
        }
    }
    return arr;
};
/**
 * 平级结构转数树结构
 * @param score
 * @param pid
 */
function convertLevelToTree(score, pid = null) {
    const tree = [];
    score.map((item) => {
        if (item.pid === pid) {
            // 递归寻找
            item.children = convertLevelToTree(score, item.id);
            tree.push(item);
        }
    });
    return tree;
}
//数组去重
function unique(arr) {
    const resIds = [];
    const res = [];
    for (let i = 0; i < arr.length; i++) {
        if (!resIds.includes(arr[i].fid)) {
            resIds.push(arr[i].fid);
            res.push({
                ...arr[i],
            });
        }
    }
    return res;
}
/**
 * 根据length计算数据深度
 */
export function arrayDeepLevel(arr) {
    if (Array.isArray(arr)) {
        let maxDepth = -2;
        for (let i = 0; i < arr.length; i++) {
            const depth = arrayDeepLevel(arr[i].children);
            if (depth > maxDepth) {
                maxDepth = depth;
            }
        }
        return maxDepth + 1;
    }
    else {
        return -2;
    }
}
export function copyToClipboard(value) {
    let input = document.querySelector(".copy-input") || document.createElement("textarea");
    input.className = "copy-input";
    input.value = value;
    input.style = `position: fixed;top: -100%;`;
    document.body.append(input);
    input.select();
    //虽然要废弃，是目前兼容性最好的方案.
    document.execCommand("copy");
}
/**
 * 自定义toFixed: 解决原生toFixed精度丢失问题
 * @param {*} num
 * @param {*} decimals
 * @returns
 */
export function toFixed(num, decimals) {
    const factor = Math.pow(10, decimals);
    return (Math.round(num * factor) / factor).toFixed(decimals);
}
//格式化千分位符
export function formatPrice(price) {
    return String(toFixed(price, 2)).replace(/\B(?=(\d{3})+(?!\d))/g, ",");
}
//创建随机数的代码
export function generateVersionCode() {
    return `const version = ${Math.random()}`;
}
/**
 * 获取小数位
 * @param val
 */
export function getDpLen(val) {
    const str_val = val.toString();
    const split_val = str_val.split(".");
    if (split_val.length > 1) {
        return split_val[1].length;
    }
    else {
        return 0;
    }
}
//节流事件
export function throttle(fn, time = 300) {
    var t = null;
    return function (...rest) {
        if (t)
            return;
        t = setTimeout(() => {
            fn.apply(this, rest);
            t = null;
        }, time);
    };
}
/**
 * 获取本年度
 */
// export function getDataId() {
//   const sessionObj =
//     JSON.parse(sessionStorage.getItem("electronParams")) || null;
//   let yearVal: any;
//   if (sessionObj) {
//     yearVal = sessionObj.params.sjnd; // sessionStorage 中取值
//   } else {
//     const date = new Date();
//     //取不到获取用户本地时间
//     yearVal = date.getFullYear();
//   }
//   return yearVal;
// }
/**
 * 判断是否为数字
 */
export function isNumber(value) {
    if (typeof value === "number") {
        return true;
    }
    if (typeof value === "string" &&
        !isNaN(parseFloat(value)) &&
        isFinite(Number(value))) {
        return true;
    }
    return false;
}
/**
 * 最大数值处理，15位整数 , 2位小数
 */
export function maxNumberLimit(value) {
    const is_number = isNumber(value);
    const limitValue = value + ""; //转成字符串
    if (is_number) {
        let [integer, decimals] = limitValue.split(".");
        integer = integer ? integer : limitValue;
        if (integer.length > 12) {
            integer = integer.substring(0, 12);
        }
        if (decimals && decimals.length > 4) {
            decimals = decimals.substring(0, 4);
        }
        const f_number = decimals ? `${integer}.${decimals}` : `${integer}`;
        // const limit_num = new BigNumber(f_number);
        // return limit_num.toNumber();
        return f_number;
    }
    return value;
}
/**
 * 用于处理excel中的货币符号，和特殊格式化粘贴到CpasTable中的数据转换
 * @param text
 */
export function convertToNumber(text, d) {
    if (typeof text === "number" ||
        text === "" ||
        text === null ||
        text === undefined) {
        return text;
    }
    // 匹配数字的正则表达式
    const regex = /^-?([$￥¥])?([0-9,]+(\.[0-9]+)?)?([%万])?$/;
    const textCopy = text.replaceAll(" ", "");
    //检测文本是否符合数字格式
    const match = textCopy.match(regex);
    if (match) {
        // 获取货币符号、数字部分和百分比符号
        const currencySymbol = match[1];
        const numberPart = match[2];
        const decimals = match[3];
        const endSymbol = match[4];
        const isFushu = text.startsWith("-");
        if (typeof numberPart !== "string") {
            return text;
        }
        // 去除千分位符号和百分比符号
        const numberString = numberPart.replace(/[,]/g, "");
        // 转换为数字
        const num = new BigNumber(numberString);
        let number = 0;
        if (d) {
            number = parseFloat(num.toFixed(d));
        }
        else {
            number = num.toNumber();
        }
        // 如果有货币符号，则将数字乘以对应的倍数
        // if (currencySymbol === "$") {
        //   number *= 1;
        // } else if (currencySymbol === "￥") {
        //   number *= 7; // 假设1元人民币 = 7美元
        // }
        // 如果有百分比符号，则将数字除以100
        if (endSymbol === "%") {
            number /= 100;
        }
        if (endSymbol === "万") {
            number *= 10000;
        }
        if (isFushu) {
            number = number * -1;
        }
        return number;
    }
    else {
        return text;
    }
}
/**
 * 获取组成部分id
 */
export function getZcbmId() {
    const sessionObj = JSON.parse(sessionStorage.getItem("electronParams")) || null;
    let zcbmId;
    if (sessionObj) {
        zcbmId = sessionObj.params?.DBName; // sessionStorage 中取值
    }
    else {
        zcbmId = consts.defaultDbName; // "202205188806-KH202012975";
    }
    return zcbmId;
}
let currentAuditYear = null;
//只有重算，和批量重算的情况下会重置这个方法。每打开一个新的组成部分时。都是独立的一个全局变量. 如果非披露表部分使用该值。需要自己控制重置请求点
export function setCurrentAuditYear(year) {
    currentAuditYear = year;
}
/**
 * 从接口获取年度
 * @param str
 */
export async function getDataId() {
    //只有重算，和批量重算的情况下会重置这个方法。每打开一个新的组成部分时。都是独立的一个全局变量
    if (currentAuditYear) {
        return currentAuditYear;
    }
    try {
        const res = await getAuditYearApi();
        if (res.data && Array.isArray(res.data) && res.data.length > 0) {
            const year = res.data[0]["Data_ID"];
            //业务逻辑中取首页期间类型的最后一个
            currentAuditYear = year;
            return year;
        }
        else {
            return null;
        }
    }
    catch (e) {
        throw e;
    }
}
// 获取年度 下拉框
export async function getYears(str) {
    let yearVal;
    try {
        yearVal = await getDataId();
    }
    catch (e) {
        throw e;
    }
    if (!yearVal) {
        console.error("获取年度失败");
        return;
    }
    const obj = {
        上五年: Number(yearVal) - 5,
        上四年: Number(yearVal) - 4,
        上三年: Number(yearVal) - 3,
        上两年: Number(yearVal) - 2,
        上一年: Number(yearVal) - 1,
        本年: Number(yearVal),
        下一年: Number(yearVal) + 1,
        下两年: Number(yearVal) + 2,
        下三年: Number(yearVal) + 3,
    };
    return obj[str];
}
// 获取报表年度 下拉框 时间段
export async function getPdYears() {
    let yearVal;
    try {
        yearVal = await getDataId();
    }
    catch (e) {
        throw e;
    }
    if (!yearVal) {
        console.error("获取年度失败");
        return;
    }
    const obj = {
        上六期: `${Number(yearVal) - 6}`,
        上五期: `${Number(yearVal) - 5}`,
        上四期: `${Number(yearVal) - 4}`,
        上三期: `${Number(yearVal) - 3}`,
        上两期: `${Number(yearVal) - 2}`,
        上一期: `${Number(yearVal) - 1}`,
        本期: `${Number(yearVal)}`,
        下一期: `${Number(yearVal) + 1}`,
    };
    let res = [];
    for (let key in obj) {
        res.push({
            label: key,
            value: key,
        });
    }
    return res;
}
// 获取报表年度 下拉框 时间点
export async function getPtYears() {
    let yearVal;
    try {
        yearVal = await getDataId();
    }
    catch (e) {
        throw e;
    }
    if (!yearVal) {
        console.error("获取年度失败");
        return;
    }
    const obj = {
        上六年期末: `${Number(yearVal) - 6}期末`,
        上五年期末: `${Number(yearVal) - 5}期末`,
        上五年期初: `${Number(yearVal) - 5}期初`,
        上四年期末: `${Number(yearVal) - 4}期末`,
        上四年期初: `${Number(yearVal) - 4}期初`,
        上三年期末: `${Number(yearVal) - 3}期末`,
        上三年期初: `${Number(yearVal) - 3}期初`,
        上两年期末: `${Number(yearVal) - 2}期末`,
        上两年期初: `${Number(yearVal) - 2}期初`,
        上一年期末: `${Number(yearVal) - 1}期末`,
        上一年期初: `${Number(yearVal) - 1}期初`,
        本年期末: `${Number(yearVal)}期末`,
        本年期初: `${Number(yearVal)}期初`,
        下一年期末: `${Number(yearVal) + 1}期末`,
        下一年期初: `${Number(yearVal) + 1}期初`,
    };
    let res = [];
    for (let key in obj) {
        res.push({
            label: key,
            value: key,
        });
    }
    return res;
}
//获取批量交叉校验下拉
//获取交叉校验时间点数据for后端接口需要
export async function getCrossPt() {
    const res = await getPtYears();
    let list = [];
    if (res && res.length) {
        for (let i = 0; i < res.length; i++) {
            list.push(res[i].label);
        }
    }
    return list;
}
//获取交叉校验时间段数据for后端接口需要
export async function getCrossPd() {
    const res = await getPdYears();
    let list = [];
    if (res && res.length) {
        for (let i = 0; i < res.length; i++) {
            list.push(res[i].label);
        }
    }
    return list;
}
//获取批量交叉校验下拉
export const CHECK_BATCH_CROSS_PT_TYPE = [
    {
        label: "期初",
        value: "{期初}",
    },
    {
        label: "期末",
        value: "{期末}",
    },
];
export const CHECK_BATCH_CROSS_PD_TYPE = [
    {
        label: "本期",
        value: "{本期}",
    },
    {
        label: "上期",
        value: "{上期}",
    },
];
//深拷贝一个对象的函数
export function deepClone(obj) {
    if (typeof obj !== "object")
        return obj;
    if (obj === null)
        return obj;
    if (obj instanceof Date)
        return new Date(obj);
    if (obj instanceof RegExp)
        return new RegExp(obj);
    let newObj = new obj.constructor();
    for (let key in obj) {
        if (obj.hasOwnProperty(key)) {
            newObj[key] = deepClone(obj[key]);
        }
    }
    return newObj;
}
//解析excel数据并转换为cpasTable数据格式
export async function excelToCpasJSON(file, callback) {
    const reader = new FileReader();
    reader.onload = async (e) => {
        const data = e.target.result;
        /* reader.readAsArrayBuffer(file) -> data will be an ArrayBuffer */
        const workbook = await XLSX.read(data);
        const sheetName = workbook.SheetNames[0];
        const sheetTableName = workbook.SheetNames[1];
        const sheet = workbook.Sheets[sheetName];
        const sheet_json = workbook.Sheets[sheetTableName]; //此数据为json配置数据
        let currentSheetjson = XLSX.utils.sheet_to_json(sheet, {
            header: 1,
            raw: false,
            blankrows: false,
        });
        // 获取sheet表2的table配置数据
        let sheetJsonData = sheet_json
            ? XLSX.utils.sheet_to_json(sheet_json, {
                header: 1,
                raw: false,
            })[0]
            : [];
        let tableStr = "";
        for (let i = 0; i < sheetJsonData.length; i++) {
            tableStr += sheetJsonData[i];
        }
        const tableConfig = tableStr ? JSON.parse(tableStr) : {};
        const { headerNewData, newData } = mergeTableData(tableConfig, currentSheetjson);
        tableConfig.header = headerNewData;
        tableConfig.data = newData;
        callback(tableConfig);
    };
    reader.readAsArrayBuffer(file);
}
//cpastable导出到底稿平台
export async function exportDraft({ filePath, sheetName, self, }) {
    const sheetData = formatTabletoExcel({
        self,
        isEditFormula: true,
    });
    try {
        /*console.log(
          window,
          window.parent["businessService"],
          "window.businessService111"
        );*/
        const { code } = await window["businessService"].excelManageGetExcelData({
            filePath,
            sheetData,
            sheetName,
        });
        if (+code === 200) {
            message.success("操作成功");
        }
        else {
            message.error("操作失败，请重试");
        }
    }
    catch (err) {
        message.success("操作失败，请重试");
        throw err;
    }
}
/**
 * 财务报表按照报名名称/报表类型排序
 */
export function sortCpasTable(newFsData) {
    const NAME_SORT_CFG = ["未审财务报表", "试算平衡", "审定财务"]; //一级报名名称排序枚举
    const TYPE_SORT_ORDER = {
        资产: 1,
        负债: 2,
        利润: 3,
        现流: 4,
        现流附: 5,
        "权益变动(本年)": 6,
        "权益变动(上年)": 7,
        减值准备: 8,
    }; //二级报名分类排序枚举
    let nameResData = []; //按报表名称排序结果存储
    for (let i = 0; i < NAME_SORT_CFG.length; i++) {
        let temp = [];
        const name = NAME_SORT_CFG[i];
        for (let j = 0; j < newFsData.length; j++) {
            const tableName = newFsData[j].name;
            if (tableName.includes(name)) {
                temp.push(newFsData[j]);
            }
        }
        nameResData.push(temp);
    }
    let typeResData = []; //按报表分类排序结果存储
    for (let i = 0; i < nameResData.length; i++) {
        let groupData = nameResData[i].slice();
        for (let key in TYPE_SORT_ORDER) {
            for (let j = 0; j < groupData.length; j++) {
                if (groupData[j].name.includes(key)) {
                    groupData[j]["index"] = TYPE_SORT_ORDER[key];
                }
            }
        }
        groupData.map((item) => {
            if (!item.index) {
                item.index = 99;
            }
        });
        const temp = groupData.sort((a, b) => a.index - b.index);
        typeResData.push(...temp);
    }
    console.log("resData", typeResData);
    return typeResData;
}
/**
 * 数字转字母
 * @param numm
 * @returns 字母
 */
export function numToString(numm) {
    var stringArray = [];
    var numToStringAction = function (nnum) {
        var num = nnum - 1;
        var a = Math.floor(num / 26);
        var b = num % 26;
        stringArray.push(String.fromCharCode(64 + Math.floor(b + 1)));
        if (a > 0) {
            numToStringAction(a);
        }
    };
    numToStringAction(numm);
    return stringArray.reverse().join("");
}
export function rTime(date) {
    const json_date = new Date(date).toJSON();
    const Time = `${new Date(json_date)}${8 * 3600 * 1000}`;
    const attachmentTime = new Date(Time)
        .toISOString()
        .replace(/T/g, " ")
        .replace(/.[d]{3}Z/, "");
    return attachmentTime.split(".")[0];
}
// 检查字符串是否不为空且第一个字符是等号
export function isFirstCharEqual(str) {
    return str.length > 0 && str.charAt(0) === "=";
}
//交叉校验数据转换拉平
export function transformCrossData(data, noTranform = false) {
    if (!data || !data.length) {
        return [];
    }
    let newList = [];
    for (let i = 0; i < data.length; i++) {
        const { type, beVerifiedFormulaResultList, number, isForce, verifyFormula, operation, verifyFormulaResultList, } = data[i];
        if (!noTranform) {
            if (+type === 4 &&
                beVerifiedFormulaResultList &&
                beVerifiedFormulaResultList.length) {
                let childVerifysResult = [];
                for (let j = 0; j < beVerifiedFormulaResultList.length; j++) {
                    const { formula, verifyItem, value, result, formulaFormat, coords } = beVerifiedFormulaResultList[j];
                    childVerifysResult.push({
                        type,
                        checkId: `${i + 1}-${j + 1}`,
                        number: `${number}-${j + 1}`,
                        isForce,
                        beVerifiedFormula: formula,
                        fullFormula: verifyItem?.formulaFormat,
                        beVerifiedFormulaResult: value,
                        verifyFormulaResult: verifyItem?.value,
                        fullFormulaResult: result,
                        verifyFormula,
                        operation,
                        beVerifiedFormulaResultList,
                        beVerifyFormat: formulaFormat,
                        verifyFormat: verifyItem?.formulaFormat,
                        verifyFormulaList: [
                            {
                                coords: verifyItem?.coords,
                                currentFormula: verifyItem?.formula,
                            },
                        ],
                        beVerifiedCoordsMap: {
                            [formula]: coords,
                        },
                    });
                }
                if (childVerifysResult && childVerifysResult.length) {
                    data[i].childVerifysResult = childVerifysResult;
                }
            }
            else {
                data[i].checkId = i + 1;
            }
        }
        const { childVerifysResult } = data[i];
        if (+type !== 4 || noTranform) {
            newList.push(data[i]);
        }
        else if (childVerifysResult && childVerifysResult.length) {
            newList.push(...childVerifysResult);
        }
    }
    return newList;
}
export default {
    guid,
    formatPrice,
    throttle,
    getYears,
    deepClone,
    excelToCpasJSON,
    exportDraft,
};
